<template>
    <div class="flex_col_start p10 m5 card">
        <label class="flex_center_self">上传固件文件</label>
        <div class="flex_row_center mt5">
            <label>名称:</label>
            <el-input clearable class="ml5" style="width: 250px;" v-model="ctx.fileName" />
            <OpenFileButtonParts name="选择文件" accept=".hex, .bin, .apk, .exe" @opend="onFileOpen" />
        </div>
        <div class="flex_row_center mt5">
            <label>版本:</label>
            <el-input clearable class="ml5" v-model="ctx.version" style="width: 200px;" />
        </div>
        <div class="flex_row_center mt5">
            <label>描述:</label>
            <el-input class="ml5" v-model="ctx.description" type="textarea" style="width: 250px;" />
        </div>
        <div class="flex_row_center mt5 flex_center_self">
            <el-button @click="onClickCreate" type="primary">创建</el-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive } from 'vue';
import OpenFileButtonParts from './OpenFileButtonParts.vue';
import { runAction } from '@/utils/ui';
import { createFirmFile } from '@/service/firm_file';

interface Ctx {
    fileName: string,
    fileData: Uint8Array | null,
    description: string,
    version: string,
}

interface Props {
    type_id: number,
}

const props = defineProps<Props>();

const ctx = reactive<Ctx>({
    fileData: null,
    fileName: '',
    description: '',
    version: '',
});

const emit = defineEmits<{
    created: []
}>();

async function onFileOpen(name: string, data: Uint8Array) {
    ctx.fileData = data;
    ctx.fileName = name;
}

async function onClickCreate() {
    let flag = false;
    await runAction('新建', '', async (dialog) => {
        if (ctx.fileData == null) {
            throw '请选择文件';
        }
        if (ctx.fileName.length == 0) {
            throw '请选择文件/输入名称';
        }
        if (ctx.version.length == 0) {
            throw '请输入版本号';
        }
        await createFirmFile({
            type_id: props.type_id,
            name: ctx.fileName,
            body: ctx.fileData,
            version: ctx.version,
            description: ctx.description,
        }, (n: number) => {
            dialog.setMsg(`进度:${n}%`);
        });
        flag = true;
    });
    if (!flag) {
        return;
    }
    emit('created');
}



</script>
